﻿using AiBLSmartEdu.Module.AIHealthManage.API.DTOs;
using AutoMapper;
using Domain.Entities;
using Domain.Entities.HealthManages;
using FrameworkCore.DI;
using FrameworkCore.Extensions;
using FrameworkCore.Helpers;
using FrameworkCore.Interfaces;
using FrameworkCore.Models;
using FrameworkCore.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

#nullable disable

namespace AiBLSmartEdu.Module.AIHealthManage.API.Services
{
    public class HealthRecordService : IScopedDependency
    {
        private readonly IRepository<HealthRecord> _repository;
        private readonly ICurrentUserService _currentUserService;
        private readonly IMapper _mapper;
        private readonly OllamaService _ollamaService;

        public HealthRecordService(
            IRepository<HealthRecord> repository,
            ICurrentUserService currentUserService,
            IMapper mapper,
            OllamaService ollamaService)
        {
            _repository = repository;
            _currentUserService = currentUserService;
            _mapper = mapper;
            _ollamaService = ollamaService;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <param name="filter">分页输入模型</param>
        /// <returns></returns>
        public async Task<PageResult<HealthRecordOutputModel>> PageAsync(HealthRecordPaginationFilter filter)
        {
            return (await _repository.GetOrderedQueryable(query =>
            {
                return query.OrderByDescending(o => o.Id)
                .WhereIf(!filter.Keyword.IsNullOrWhiteSpace(), x => x.Result.Contains(filter.Keyword));

            }, filter).ProjectToPaginatedDataAsync<HealthRecord, HealthRecordOutputModel>(
                filter.PageNumber,
                filter.PageSize,
                _mapper.ConfigurationProvider
            )).ToPageList();
        }

        /// <summary>
        /// 获取一条健康记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns>唯一标识</returns>
        public async Task<HealthRecordOutputModel> GetByIdAsync(long id)
        {
            var entity = await _repository.GetByIdAsync(id);
            return _mapper.Map<HealthRecordOutputModel>(entity);
        }

        /// <summary>
        /// 创建健康记录
        /// </summary>
        /// <param name="model"></param>
        /// <returns>唯一标识</returns>
        public async Task<long> CreateAsync(HealthRecordCreateInputModel model)
        {
            var entity = await _repository.InsertAndGetAsync(_mapper.Map<HealthRecord>(model));
            return entity.Id;
        }

        /// <summary>
        /// 获取诊断结果
        /// </summary>
        /// <param name="id"></param>
        /// <param name="isRediagnose">是否重新诊断</param>
        /// <returns>唯一标识</returns>
        public async Task<HealthRecordOutputModel> GetResutsByIdAsync(long id, bool? isRediagnose = false)
        {
            var entity = await _repository.GetByIdAsync(id);
            ExceptionHelper.ThrowIfNull(entity, "无效的ID，查询失败");
            if (isRediagnose.HasValue && isRediagnose.Value == true) 
            {
                var analysisResponse = await _ollamaService.GenerateHealthAnalysis(entity.ToAIHealthDataJson());
                await _repository.UpdateAsync(x =>
                    x.SetProperty(p => p.Result, p => analysisResponse), w => w.Id == id);
                entity.Result = analysisResponse;
            }          

            var model = _mapper.Map<HealthRecordOutputModel>(entity);

            return model;
        }

        /// <summary>
        /// 删除健康记录
        /// </summary>
        /// <param name="id"></param>
        /// <returns>唯一标识</returns>
        public async Task DeleteAsync(long id)
        {
            var entity = await _repository.GetByIdAsync(id);
            ExceptionHelper.ThrowIfNull(entity, "无效的ID，删除失败");
            await _repository.DeleteAsync(entity);
        }
    }
}
